package com.hoolai.qps.mina.string;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import java.util.Scanner;

import org.apache.log4j.Logger;
import org.apache.mina.core.RuntimeIoException;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

import com.hoolai.qps.mina.string.ProxyServer.Msg;

public class Client {

	private static final Logger logger = Logger.getLogger(Client.class);

	private static final long CONNECT_TIMEOUT = 3000;

	public static void main(String[] args) throws InterruptedException {
		new Client(new MessageProcess());
	}
	
	public Client() {
        }

	public static class MessageProcess {
		public void sendMessage(IoSession session) {
			Scanner sc = new Scanner(System.in);
			while (true) {
				String message = sc.next();
				if (message == "exit") {
					break;
				}
				Msg msg = new Msg(100, 1001000, message);
				session.write(msg.toString());
			}
			session.close(true);
		}
	}

	public Client(MessageProcess message) throws InterruptedException {
		NioSocketConnector connector = getConnector();
	        
		try {
			ConnectFuture future = connector.connect(new InetSocketAddress("127.0.0.1", 2222));
			future.awaitUninterruptibly();
			IoSession session = future.getSession();
			message.sendMessage(session);
		} catch (RuntimeIoException e) {
			System.err.println("Failed to connect.");
			e.printStackTrace();
			Thread.sleep(5000);
		}
	}
	
	protected NioSocketConnector getConnector(){
	    NioSocketConnector connector = new NioSocketConnector(4);
            connector.setConnectTimeoutMillis(CONNECT_TIMEOUT);
//            connector.getFilterChain().addLast("codec",
//                            new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8"))));
            connector.setHandler(new ClientHandler());
            return connector;
	}
	
	private class ClientHandler extends IoHandlerAdapter{
		  @Override
          public void messageReceived(IoSession session, Object message) throws Exception {
                  logger.info("client message received:" + message);
          }

		@Override
		public void exceptionCaught(IoSession session, Throwable cause)
				throws Exception {
			System.err.println("client :"+cause.getMessage());
		}
	}

}
